//https://gitee.com/Ghobam/jsutils/raw/master/MyUtils.js

const urlReg = new RegExp('(^(#|javascript)|@|(\\.jpg|\\.png|\\.jpeg|\\.bmp|\\.gif|\\.css|\\.js|\\.ico|\\.mov|\\.mp4|\\.pdf|\\.zip|\\.rar|\\.doc|\\.docx|\\.xls|\\.xlsx)$)', 'i') 

function getXpExpList(keywords) {
    let kwList = keywords.split('|')
    const expList = []
    kwList.forEach((kw) => {
        expList.push(`text()="${kw}"`)
        expList.push(`text()[contains(., "${kw}")]`)
    })
    return expList;
}

function isValidUrl(url) {
    return !!url && !url.split('?')[0].match(urlReg)
}

function getUrl(elem) {
    let curElem = null
    // 如果当前节点有href，直接返回
    if (elem.hasAttribute('href')) curElem = elem
    else {
        // 没有就看看子节点有没有href
        const childHrefElems = document.evaluate( './/*[@href]', elem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null)
        if (!!childHrefElems.snapshotLength) curElem = childHrefElems.snapshotItem(0)
        // 看看父级节点是不是href
        else if (elem.parentNode.hasAttribute('href')) curElem = elem.parentNode
        // 看看兄弟节点
        else {
            if(!!elem.nextElementSibling && elem.nextElementSibling.hasAttribute('href')) curElem = elem.nextElementSibling
            else if (!!elem.previousElementSibling && elem.previousElementSibling.hasAttribute('href')) curElem = elem.previousElementSibling
        }
    }
    return (!!curElem && isValidUrl(curElem.getAttribute('href'))) ? curElem.href : ''
}

function isAutoma(elem) {
    return !elem || elem.innerHTML.includes('automa')
}

function isSameUrl(url1, urls) {
    return !!url1 && !!urls && !!urls.length && urls.some((u) => !!u && url1.split(':')[1] === u.split(':')[1])
}

function getText(elem) {
    if (!elem) return ''
    const content = (elem.innerText || elem.textContent || elem.text)
    return !!content ? content.trim() : ''
}

function isMathcedHead(exp) {
    const elems = [...Array.from(document.querySelectorAll('title,h1,h2,h3,h4,h5,h6')), ...Array.from(document.querySelectorAll('*[class*="title"]'))];
    return !!elems && !!elems.lentgh && elems.some((e) => {
        const tagName = e.parentElement.tagName
        if (['LI', 'A'].includes(tagName)) return false
        const aElem = e.querySelector('a')
        if (!!aElem) return false
        const content = getText(e)
        return !!content && content.match(exp)
    })
}

function hasTargetElem(exp) {
    const elems = document.evaluate(exp, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    if (!elems || !elems.snapshotLength) return false;

    for (let i = 0; i < elems.snapshotLength; i ++) {
        const elem = elems.snapshotItem(i)
        if (isAutoma(elem)) continue
        return true
    }

    return false
}

function unique(arr,val) {
    const res = new Map();
    return arr.filter(item => !res.has(item[val]) && res.set(item[val], 1))
}

function hasTargetColTitle(elems, keys) {
  let es = Array.from(elems);
  let nKeys = typeof keys === 'string' ? keys.split(',') : [...keys];
  if (es.length < nKeys.length) return false;
  for (let i = 0; i < es.length; i ++) {
    if (!nKeys.length) break;
    for (let j = 0; j < nKeys.length; j ++) {
      if (!!es[i].innerText.match(nKeys[j])) {
        nKeys.splice(j, 1);
        break;
      }
    }
  }

  return !nKeys.length;
}

function createParah(text) { 
    const e = document.createElement("div"); 
    e.style.cssText = 'text-align: center; background: black; color: white; position: fixed; width: 100%; z-index: 99999; font-size: 22px; top: 0; left: 0;';
    e.appendChild(document.createTextNode(text)); 
    document.body.insertBefore(e, document.body.firstChild); 
} 

const getElems = (keys) => keys.map((k) => ({ name: k, rex: `//dd//a[text()="${k}"]` })).filter((k) => !!document.evaluate(k.rex, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength);

function getData(i) {
    const elems = Array.from(document.querySelectorAll('div.filter dl')[i].querySelectorAll('& > dd > a'));
    return elems.map((e, index) => ({ name: e.innerText.trim(), rex: `(//div[@class="filter"]//dl)[${i + 1}]/dd/a[${index + 1}]` }));
}
  
function xmlEscape(text) {
    return text
    .replace(/&/g, "&amp;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;")
    .replace(/@/g, "&#64;")
    .replace(/_/g, "&#95")
    .replace(/=/g, "&#61")
    .replace(/;/g, "&#59")
    .replace(/-/g, "&#45")
    .replace(/,/g, "&#44");
}

function getHMSTime(timestamp) {
    let times = new Date(timestamp);
    return formatTime(times.getUTCHours()) + ':' + formatTime(times.getMinutes()) + ':' + formatTime(times.getSeconds());
}

function formatTime(time) {
    return String(time).padStart(2, '0');
}

function getGUID(maxLen = 10) {
    return Math.floor(Math.random() * (Math.pow(16, maxLen) - 1)).toString(16).padStart(maxLen, '0')
}

function getCurrentDate(timestamp) {
    let date = timestamp ? new Date(timestamp * 1000) : new Date();
    let month = getFormattedTime(date.getMonth() + 1);
    let day = getFormattedTime(date.getDate());
    let hours = getFormattedTime(date.getHours());
    let minutes = getFormattedTime(date.getMinutes());
    let second = getFormattedTime(date.getSeconds());
    return `${date.getFullYear()}-${month}-${day} ${hours}:${minutes}:${second}`
}

function getFormattedTime(s) {
    return String(s).padStart(2, '0');
}